<template>
  <div class="tree-box">
    <div class="left-box">
      <el-input
        class="filter-box"
        placeholder="输入关键字进行过滤"
        v-model="filterText">
        <section slot="append" v-if="$route.query.key">
          <el-button type="primary" size="mini" @click="addOrganization('')">新增组织</el-button>
        </section>
      </el-input>
      <section class="tree-box-height">
        <el-tree :data="treeData"
                  accordion
                  :props="defaultProps"
                  ref="tree"
                  :filter-node-method="filterNode"
                  @node-click="oriClick">
          <div class="custom-tree-node" style="width:100%;" slot-scope="{ node, data }">
            <div class="flex align-center flex-1">
              <i class="icon el-icon-s-shop" v-if="data.type == 1"></i>
              <i class="icon el-icon-s-ticket" v-if="data.type == 2"></i>
              <i class="m-l-s flex align-center one-line-ellipsis" style="width:50%;">{{ data.name }}</i>
            </div>
            <div class="flex align-center">
              <el-button class="tree-btn" type="text" size="mini" v-if="data.type == 1 && (groupOrStation(data.children) == 'station' || !data.children || data.children.length == 0)" @click.stop="addStation(data)">添加岗位</el-button>
              <el-button class="tree-btn" type="text" size="mini" v-if="data.type == 1 && (groupOrStation(data.children) == 'group' || !data.children || data.children.length == 0)" @click.stop="addOrganization(data)">添加团队</el-button>
              <el-button class="tree-btn warning" type="text" size="mini" v-if="data.type == 1" @click.stop="editOrganization(data)">编辑组织</el-button>
              <el-button class="tree-btn warning" type="text" size="mini" v-if="data.type == 2" @click.stop="editStation(data)">编辑岗位</el-button>
              <el-button class="tree-btn danger" type="text" size="mini" @click.stop="deleteFn(data,node)">删除</el-button>
            </div>
          </div>
        </el-tree>
      </section>
    </div>
    <div class="right-box">
      <section class="right-header-box" v-if="showRightGroup">{{currentData.name}}</section>
      <section class="right-header-box" v-if="showRightStation">{{currentData.name}}</section>
      <section class="right-header-box" v-if="showRightTree">{{currentData.name}}角色权限</section>
      <el-form ref="formGroup" :model="modelOgz" label-width="120px" v-if="showRightGroup">
        <el-row class="row">
          <el-col :span="24">
            <el-form-item label="负责人">
              <el-select class="full-width" clearable v-model="modelOgz.manager" filterable remote reserve-keyword placeholder="请搜索" :remote-method="remoteMethod" :loading="loading">
                <el-option v-for="item in userList" :key="item.primaryKey" :label="item.employeeName" :value="item.primaryKey"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="组织名称" prop="orgName" :rules="[{ required: true, message: '请输入组织名称', trigger: 'blur' }]">
              <el-input maxlength="50" v-model="modelOgz.orgName" placeholder="请输入" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="团队类型">
              <el-select size="small" clearable v-model="modelOgz.orgProjectType">
                  <el-option v-for="item in orgProjectTypeList" :key="item.key" :label="item.value" :value="item.key"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="原组织编码" prop="sourceKey">
              <el-input maxlength="200" v-model="modelOgz.sourceKey" placeholder="请输入" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-form ref="formStation" :model="modelSta" label-width="120px" v-if="showRightStation">
        <el-row class="row">
          <el-col :span="24">
            <el-form-item label="岗位名称" prop="positionName" :rules="[{ required: true, message: '请输入岗位名称', trigger: 'blur' }]">
              <el-input maxlength="50" v-model="modelSta.positionName" placeholder="请输入" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="岗位类型" prop="positionCode" :rules="[{ required: true, message: '请选择岗位类型', trigger: '' }]">
              <el-select v-model="modelSta.positionCode" clearable filterable>
                <el-option v-for="item in stationList" :key="item.dictKey" :label="item.dictKeyName" :value="item.dictKey" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-tree :data="treeMenu"
                ref="menuTree"
                class="tree-box-height-auth"
                show-checkbox
                :props="defaultMenuProps"
                :default-checked-keys="isChoseTree"
                node-key="primaryKey"
                v-if="showRightTree"
                @check-change="handleCheckChange">
        <span class="custom-tree-node" slot-scope="{ node }">
          <span>{{ node.label }}</span>
        </span>
      </el-tree>
      <div class="btn-box" v-if="showRightStation || showRightGroup || (showRightTree && treeMenu.length > 0) ">
        <el-button size="small" type="primary" @click="save" class="default-button f-right">保存</el-button>
      </div>
    </div>
  </div>
</template>
<script>
// tree中的节点类型:type => 1,组织 2,岗位 3,人员
import * as Port from "../../../api";
import { formValid } from '@/lib/utils'
import { requestTips,askDialog } from "../../../assets/util"

export default {
  data() {
    return {
      infoData: {},
      treeData: [],
      treeMenu: [],
      defaultProps: {
        children: 'children',
        label: 'name',
      },
      filterText: '',
      defaultMenuProps: {
        children: 'children',
        label: 'name',
      },
      modelOgz: {
        orgName: '',
        sourceKey: '',
        manager: '',
        orgProjectType:'',
      },
      modelSta: {
        positionName: '',
        positionCode: '',
      },
      organizeList: [],
      stationList: [],
      showRightStation: false,
      showRightGroup: false,
      showRightTree: false,
      currentData:{},
      isEdit:false,
      rootKey:"",
      userList:[],
      loading:false,
      deleteLock:false,
      isChoseTree: [],
      menuPrimaryKeys: [],
      orgProjectTypeList:[
        {key: 'ziguanProject', value:'项目'},
        {key: 'ziguanRenLi', value:'人力'},
        {key: 'ziguanXingZheng', value:'行政'},
        {key: 'ziguanCaiWu', value:'财务'},
        {key: 'ziguanQiTa', value:'其它'},
      ]
    };
  },
  created() {
    // 获取默认的企业key
    if (!this.$route.query.key && localStorage.getItem('userEnterpriseid') && this.$route.query.isAdd != 1) {
      this.$route.query.key = localStorage.getItem('userEnterpriseid')
    }
  },
  mounted () {
    if (this.$route.query.key) {
      this.getData()
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    //数据源
    async getData() {
      if (this.$route.query.key) {
        let res = await Port.apiEnterpriseInfo(this.$route.query.key);
        this.infoData = res;
        this.getInfo()
      }
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    //字典
    async getCommonData () {
      let res = await Port.apiCommonData({dictType: "ziguan_position_role_type"})
      this.stationList = res.rows || []
    },
    //数据源
    async getInfo() {
        this.getCommonData()
        let res = await Port.apiOrganizationTree({
          rootPrimaryKey:this.infoData.structureCode,
          ifGetPosition:true,
          enterpriseid:this.infoData.key,
        })
        this.treeData = res.tree[0].children || []
        this.rootKey = res.tree[0].key
        this.showRightStation = false
        this.showRightGroup = false
        this.showRightTree = false
        this.currentData = {}
        // 筛选
        this.$nextTick(() => {
          this.$refs.tree.filter(this.filterText);
        })
    },
    //右侧权限树
    async getLimitTree() {
      this.isChoseTree = [];
      let res = await Port.apiPostTree({
        enterpriseid:this.infoData.key,
        bizId:this.currentData.roleKey
      })
      this.treeMenu = res.rows || []
      if (res.rows.length > 0) {
        this.setCheckedFn(res.rows)
      }
      setTimeout(() => {
        this.handleCheckChange()
      })
    },
    setCheckedFn (list) {
      list.forEach((item) => {
        if (item.isUsed && (!item.children || item.children.length == 0)) {
          this.isChoseTree.push(item.primaryKey)
        }
        if (item.children && item.children.length > 0) {
          this.setCheckedFn(item.children)
        }
      })
    },
    //添加组织
    async addOrganization(data) {
      this.isEdit = false
      this.currentData = data
      for (var i in this.modelOgz) {
        this.modelOgz[i] = ''
      }
      this.controlRightHide('showRightGroup')
    },
    //编辑组织
    async editOrganization(data) {
      this.isEdit = true
      this.currentData = data
      let res = await Port.apiGroupInfo(data.key)
      this.remoteMethod(res.managerName)
      this.modelOgz.orgProjectType = ''
      this.orgProjectTypeList.forEach(item=>{
        if (item.key == res.orgProjectType) {
          this.modelOgz.orgProjectType = item.value;
        }
      })
      // this.modelOgz.orgProjectType = res.orgProjectType
      this.modelOgz.primaryKey = res.primaryKey
      this.modelOgz.orgName = res.orgName
      this.modelOgz.manager = res.manager
      this.modelOgz.sourceKey = res.sourceKey
      this.modelOgz.parentPrimaryKey = data.parentKey
      this.controlRightHide('showRightGroup')
    },
    //添加岗位
    async addStation(data) {
      this.isEdit = false
      this.currentData = data
      this.modelSta.positionName = ''
      this.modelSta.positionCode = ''
      this.controlRightHide('showRightStation')
    },
    //编辑岗位
    async editStation(data) {
      this.isEdit = true
      let res = await Port.apiJobInfo(data.key)
      this.currentData = data
      this.modelSta.organizationKey = res.organizationKey
      this.modelSta.positionName = res.positionName
      this.modelSta.positionCode = res.positionCode
      this.modelSta.primaryKey = res.primaryKey
      this.controlRightHide('showRightStation')
    },
    //删除
    async deleteFn(data) {
      this.deleteLock = false
      this.isEdit = false
      if (data.type == 1) {
        this.judgeHasStation(data.children)
        if (this.deleteLock) {
            this.$message.warning('该组织下有岗位，无法删除！');
          return
        }
        askDialog("是否删除该组织？",async () => {
            const res = await Port.apiGroupDel({primaryKey:data.key,enterpriseid:this.infoData.key})
            requestTips(res,()=>{
              this.getInfo()
            })
        })
      } else {
        askDialog("是否删除该岗位？",async () => {
            const res = await Port.apiJobDel(data.key)
            requestTips(res,()=>{
              this.getInfo()
            })
        })
      }
    },
    //判断子节点存不存在组织
    judgeHasStation (list) {
      // console.log(list)
      if (list && list.length > 0) {
        list.forEach(item=>{
          if (item.type == 2) {
            this.deleteLock = true
          }
          if (item.children && item.children.length > 0) {
            this.judgeHasStation(item.children)
          }
        })
      }
    },
    //所有保存
    async save() {

      if (this.showRightStation) {
        formValid(this, 'formStation', this.saveStationFn)
      } else if (this.showRightGroup){
        formValid(this, 'formGroup', this.saveGroupFn)
      } else {
        this.saveLimitFn()
      }
    },
    //保存岗位
    async saveStationFn(){
      this.orgProjectTypeList.forEach(item=>{
        if (item.value == this.modelOgz.orgProjectType) {
          this.modelOgz.orgProjectType = item.key;
        }
      })
      let param = {
        structureCode:this.infoData.structureCode,
        rootPrimaryKey:this.infoData.structureCode,
        enterpriseid:this.infoData.key,
        ...this.modelSta
      }
      if (!this.isEdit) {
        param.organizationKey = this.currentData.key
      }
      let res = this.isEdit ? await Port.apiJobEdit(param) : await Port.apiJobAdd(param)
      requestTips(res,()=>{
        this.getInfo()
      })
    },
    //保存组织
    async saveGroupFn(){
      // console.log(this.currentData)
      this.orgProjectTypeList.forEach(item=>{
        if (item.value == this.modelOgz.orgProjectType) {
          this.modelOgz.orgProjectType = item.key;
        }
      })
      let param = {
        structureCode:this.infoData.structureCode,
        rootPrimaryKey:this.infoData.structureCode,
        enterpriseid:this.infoData.key,
        orgType: '5',
        ...this.modelOgz
      }
      if (!this.isEdit) {
        param.parentPrimaryKey = this.currentData.key ? this.currentData.key : this.rootKey
      }
      let res = this.isEdit ? await Port.apiGroupEdit(param) : await Port.apiGroupAdd(param)
      requestTips(res,()=>{
        this.getInfo()
      })
    },
    //保存权限
    async saveLimitFn(){
      let res = await Port.apiDoAuth({
        bizId: this.currentData.roleKey,
        bizType:"role",
        enterpriseid:this.infoData.key,
        menuIds:this.menuPrimaryKeys
      })
      // requestTips(res,()=>{
      //   this.getInfo()
      // })
      this.getLimitTree()
      this.$message({
        type: 'success',
        message: '保存成功'
      })
    },
    //点击组织树
    oriClick(data) {
      // console.log(data);
      if (data.type == 2) {
        this.currentData = data
        this.isEdit = false
        this.controlRightHide('showRightTree')
        this.getLimitTree()
      }
    },
    //控制右侧显隐
    controlRightHide (type) {
      let list = ["showRightStation","showRightGroup","showRightTree"]
      list.forEach(item=>{
        if (item != type) {
          this[item] = false
        }
      })
      this[type] = true
    },
    //判断是否能添加岗位或者组织
    groupOrStation (list) {
      let type = ''
      if (list && list.length > 0) {
        type = list[0].type == 1 ? "group" : 'station'
      }
      return type
    },
    //搜索人
    async remoteMethod(e) {
      let res = await Port.apiUserList({
        enterpriseid:this.infoData.key,
        employeeName:e
      })
      this.userList = res.rows || []
    },
    // 选择树
    handleCheckChange () {
      let res = this.$refs.menuTree.getCheckedNodes(false, true)
      let arr = []
      res.forEach((item) => {
        arr.push(item.primaryKey)
      })
      this.menuPrimaryKeys = arr
    }
  },
};
</script>
<style lang="scss" scoped>
  .filter-box {
    margin-bottom: 15px;
  }

  .tree-box-height {
    height: calc(100vh - 160px);
    overflow: auto;
  }

  .tree-box-height-auth {
    max-height: calc(100vh - 190px);
    overflow: auto;
  }

  .btn-box{
    width: 100%;
    overflow: hidden;
  }

  .right-header-box {
    font-size: 18px;
    line-height: 50px;
    font-weight: bold;
  }
</style>
